<?php

namespace app\admin\controller;


use think\Cache;
use think\Config;
use think\Session;
use utils\PwdUtil;
use app\common\model\Admin as AdminModel;

class Index extends AdminCommon
{

    public function clear(){
        if(Cache::clear()){
            $this->success('清除成功');
        }else{
            $this->error('清除失败');
        }
    }


    /**
     * 退出
     * @desc 退出
     */
    public function logout(){
        Session::clear();
        $this->success('退出成功','admin/index/login');
    }
    /**
     * 登录
     * @desc 登录
     */
    public function login()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $params = $this->request->param();
            $admin = AdminModel::get(['admin_name' => $params['admin_name']]);
            if ($admin) {
                $pwd = PwdUtil::encode($params['pwd'] . $admin['salt']);
                if ($admin['pwd'] != $pwd) {
                    $this->error('帐号或密码错误');
                } else {
                    //将管理员数据存到session，留待持续登录验证
                    Session::set(Config::get('admin_token'), PwdUtil::encode($admin->toArray()));
                    //登录成功跳转
                    $this->success('登录成功',url('admin/index/index'));
                }
            } else {
                $this->error('帐号或密码错误');
            }
        }
        return $this->fetch();
    }

    /**
     * 首页
     * @desc 首页
     */
    public function index()
    {
        $this->view->engine->layout('public/layout');
        return $this->fetch();
    }

    /**
     * 上传图片
     * @desc 上传图片
     */
    public function upload($path)
    {
        $file = $this->request->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            $file_dir = ROOT_PATH . 'public' . DS . 'upload' . DS . $path;
            $info = $file->move($file_dir);
            if ($info) {
                $url_path = DS . 'upload' . DS . $path . DS . $info->getSaveName();
                $this->success('上传图片成功', '', ['url' => $url_path]);
            } else {
                $this->error($info->getError());
            }
        }
    }

}
